package com.iwhalecloud.bss.kite.cucc.order.accept.constructor.inst;

import com.iwhalecloud.bss.kite.common.constant.TableConsts;
import com.iwhalecloud.bss.kite.common.util.SeqUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.ProductCache;
import com.iwhalecloud.bss.kite.dataservice.entity.inst.ProdInstRel;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.ProdRelInfo;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Product;
import com.iwhalecloud.bss.kite.dataservice.mapper.inst.ProdInstRelMapper;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInstFunc;
import com.iwhalecloud.bss.kite.manager.inst.graph.impl.RelEdge;
import com.iwhalecloud.bss.kite.manager.util.RelTypeUtils;
import com.iwhalecloud.bss.kite.order.client.dto.OrderRequest;
import com.ztesoft.bss.base.staticdata.CoreDataPublic;
import com.ztesoft.bss.common.util.SpringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 产品实例关系构造器
 * @version 1.0
 */
@Component
public class ProdInstRelConstructor extends RelConstructor<ProdInstRel> {

    @Override
    public String getTableName() {
        return TableConsts.ProdInstRel.getTableName();
    }

    @Override
    public ProdInstRel newInst(OrderRequest orderRequest, RelEdge relEdge, String prodInstRelId) {
        if (!ObjectUtils.allNotNull(orderRequest, relEdge)) {
            return null;
        }

        KiteInst aInst = getInst(orderRequest.getCustId(), relEdge.getSourceInstType(), relEdge.getSourceInstId());
        KiteInst zInst = getInst(orderRequest.getCustId(), relEdge.getTargetInstType(), relEdge.getTargetInstId());
        if (Objects.isNull(aInst) || Objects.isNull(zInst)) {
            return null;
        }

        String aCompInstId = aInst.getCompInstId();
        String zCompInstId = zInst.getCompInstId();

        String aProdId = aInst.getSpecId();
        String zProdId = zInst.getSpecId();
        String relType = RelTypeUtils.getRelTypeCode(relEdge);
        ProdRelInfo prodRel = getProdRel(aProdId, zProdId, relType);
        String prodRelId = Optional.ofNullable(prodRel).map(ProdRelInfo::getProdRelId).orElse(null);
        String roleId = relEdge.getRoleId();
        roleId = StringUtils.isNotBlank(roleId) ? roleId
            : Optional.ofNullable(prodRel).map(ProdRelInfo::getRoleId).orElse("-1");

        Date now = new Date();
        ProdInstRel prodInstRel = new ProdInstRel();
        if (StringUtils.isNotBlank(prodInstRelId)) {
            prodInstRel.setProdInstRelId(prodInstRelId);
        }
        else {
            prodInstRel.setProdInstRelId(SeqUtils.getNext(TableConsts.ProdInstRel));
        }
        prodInstRel.setOwnerCustId(orderRequest.getCustId());
        prodInstRel.setActionType(ActionType.A.name());
        prodInstRel.setRelatedCompInstId(zCompInstId);
        prodInstRel.setRelationId(prodRelId);
        prodInstRel.setRelType(relType);
        prodInstRel.setCreateDate(now);
        prodInstRel.setStatusCd(CoreDataPublic.PUB_C_0001_1200);
        prodInstRel.setCompInstId(aCompInstId);
        prodInstRel.setStatusDate(now);
        prodInstRel.setCreateStaff(orderRequest.getStaffId());
        prodInstRel.setRelTableName(relEdge.getRelTableName());
        prodInstRel.setRelFieldName(relEdge.getRelFieldName());
        prodInstRel.setLanId(orderRequest.getLanId());
        prodInstRel.setUpdateStaff(orderRequest.getStaffId());
        prodInstRel.setUpdateDate(now);
        prodInstRel.setLastOrderItemId("-1");
        prodInstRel.setRoleId(roleId);
        prodInstRel.setaProdInstId(relEdge.getSourceInstId());
        prodInstRel.setzProdInstId(relEdge.getTargetInstId());

        // 设置Z端产品实例号码和本地网(全国亲情网)
        if (zInst instanceof KiteProdInst) {
            KiteProdInst zProdInst = (KiteProdInst) zInst;
            prodInstRel.setzAccNum(zProdInst.getAccNum());
            prodInstRel.setzLanId(zProdInst.getLanId());
        }

        return prodInstRel;
    }

    @Override
    public ProdInstRel getInstRel(String aProdInstId, String zProdInstId, String relType, String custId) {
        Example example = new Example(ProdInstRel.class);
        Criteria criteria = example.createCriteria().andEqualTo("aProdInstId", aProdInstId)
            .andEqualTo("zProdInstId", zProdInstId).andEqualTo("relType", relType);
        if (StringUtils.isNotBlank(custId)) {
            criteria.andEqualTo("ownerCustId", custId);
        }
        ProdInstRelMapper mapper = SpringUtil.getBean(ProdInstRelMapper.class);
        List<ProdInstRel> prodInstRels = mapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(prodInstRels)) {
            ProdInstRel prodInstRel = prodInstRels.get(0);
            if (Objects.equals(ActionType.A.name(), prodInstRel.getActionType())) {
                prodInstRel.setNewActionType(ActionType.K.name());
            }
            return prodInstRel;
        }

        return null;
    }

    /**
     * 获取产品关系规格数据
     * @param aProdId
     * @param zProdId
     * @param relType
     * @return
     */
    private ProdRelInfo getProdRel(String aProdId, String zProdId, String relType) {
        if (StringUtils.isAnyBlank(aProdId, zProdId, relType)) {
            return null;
        }

        Product aProdInst = ProductCache.get(aProdId);
        if (Objects.isNull(aProdInst)) {
            return null;
        }

        List<ProdRelInfo> prodRels = aProdInst.listProdRels();
        for (ProdRelInfo prodRel : prodRels) {
            if (StringUtils.equalsAny(prodRel.getaProdId(), aProdId, zProdId)
                && StringUtils.equalsAny(prodRel.getzProdId(), aProdId, zProdId)
                && StringUtils.equals(relType, prodRel.getRelType())) {
                return prodRel;
            }
        }

        return null;
    }

    /**
     * 获取接入产品或功能产品实例，并补充compInstId
     * @param custId
     * @param instType
     * @param instId
     * @return
     */
    private KiteInst getInst(String custId, InstType instType, String instId) {
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        KiteInst inst = querySceneInstService.getKiteInst(custId, instType, instId);
        if (Objects.nonNull(inst) && StringUtils.isBlank(inst.getCompInstId())) {
            if (inst instanceof KiteProdInstFunc) {
                KiteProdInst prodInst = querySceneInstService.getProdInstByFuncProdInstId(custId, inst.getInstId());
                inst.setCompInstId(Optional.ofNullable(prodInst).map(KiteProdInst::getOfferInstId).orElse(null));
            }
            else if (inst instanceof KiteProdInst) {
                inst.setCompInstId(((KiteProdInst) inst).getOfferInstId());
            }
        }

        return inst;
    }
}
